import { ElMessage } from 'element-plus'

// WebSocket连接管理
class RealtimeManager {
  private ws: WebSocket | null = null
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectInterval = 3000
  private heartbeatInterval: NodeJS.Timeout | null = null
  private messageHandlers: Map<string, Function[]> = new Map()

  // 连接WebSocket
  connect(url: string) {
    try {
      this.ws = new WebSocket(url)
      
      this.ws.onopen = () => {
        console.log('WebSocket连接成功')
        this.reconnectAttempts = 0
        this.startHeartbeat()
      }
      
      this.ws.onmessage = (event) => {
        this.handleMessage(event.data)
      }
      
      this.ws.onclose = () => {
        console.log('WebSocket连接关闭')
        this.stopHeartbeat()
        this.attemptReconnect()
      }
      
      this.ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error)
      }
    } catch (error) {
      console.error('WebSocket连接失败:', error)
    }
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.stopHeartbeat()
  }

  // 发送消息
  send(type: string, data: any) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify({ type, data }))
    }
  }

  // 订阅消息
  subscribe(type: string, handler: Function) {
    if (!this.messageHandlers.has(type)) {
      this.messageHandlers.set(type, [])
    }
    this.messageHandlers.get(type)!.push(handler)
  }

  // 取消订阅
  unsubscribe(type: string, handler: Function) {
    const handlers = this.messageHandlers.get(type)
    if (handlers) {
      const index = handlers.indexOf(handler)
      if (index > -1) {
        handlers.splice(index, 1)
      }
    }
  }

  // 处理接收到的消息
  private handleMessage(data: string) {
    try {
      const message = JSON.parse(data)
      const { type, payload } = message
      
      const handlers = this.messageHandlers.get(type)
      if (handlers) {
        handlers.forEach(handler => handler(payload))
      }
      
      // 特殊消息处理
      this.handleSpecialMessages(type, payload)
    } catch (error) {
      console.error('消息解析失败:', error)
    }
  }

  // 处理特殊消息
  private handleSpecialMessages(type: string, payload: any) {
    switch (type) {
      case 'notification':
        this.showNotification(payload)
        break
      case 'performance_update':
        this.handlePerformanceUpdate(payload)
        break
      case 'artist_update':
        this.handleArtistUpdate(payload)
        break
      case 'vote_update':
        this.handleVoteUpdate(payload)
        break
    }
  }

  // 显示通知
  private showNotification(notification: any) {
    ElMessage({
      message: notification.message,
      type: notification.type || 'info',
      duration: 5000
    })
  }

  // 处理演出更新
  private handlePerformanceUpdate(payload: any) {
    // 触发演出数据更新事件
    window.dispatchEvent(new CustomEvent('performance-update', { detail: payload }))
  }

  // 处理艺人更新
  private handleArtistUpdate(payload: any) {
    // 触发艺人数据更新事件
    window.dispatchEvent(new CustomEvent('artist-update', { detail: payload }))
  }

  // 处理投票更新
  private handleVoteUpdate(payload: any) {
    // 触发投票数据更新事件
    window.dispatchEvent(new CustomEvent('vote-update', { detail: payload }))
  }

  // 尝试重连
  private attemptReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
      
      setTimeout(() => {
        if (this.ws) {
          this.connect(this.ws.url)
        }
      }, this.reconnectInterval * this.reconnectAttempts)
    }
  }

  // 开始心跳
  private startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      this.send('ping', { timestamp: Date.now() })
    }, 30000) // 30秒发送一次心跳
  }

  // 停止心跳
  private stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  }
}

// 创建单例实例
export const realtimeManager = new RealtimeManager()

// 实时功能工具函数
export const realtimeUtils = {
  // 连接实时服务
  connect() {
    const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:3000/ws'
    realtimeManager.connect(wsUrl)
  },

  // 断开连接
  disconnect() {
    realtimeManager.disconnect()
  },

  // 订阅演出更新
  subscribePerformanceUpdates(callback: Function) {
    realtimeManager.subscribe('performance_update', callback)
  },

  // 订阅艺人更新
  subscribeArtistUpdates(callback: Function) {
    realtimeManager.subscribe('artist_update', callback)
  },

  // 订阅投票更新
  subscribeVoteUpdates(callback: Function) {
    realtimeManager.subscribe('vote_update', callback)
  },

  // 订阅通知
  subscribeNotifications(callback: Function) {
    realtimeManager.subscribe('notification', callback)
  },

  // 发送投票
  sendVote(artistId: number) {
    realtimeManager.send('vote', { artistId })
  },

  // 发送位置更新
  sendLocation(location: { lat: number; lng: number }) {
    realtimeManager.send('location', location)
  }
}

export default realtimeManager
